package com.example.demo.utils;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.example.demo.config.GlobalConfig;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;

/**
 *扫脸登录相关工具类
 * @author zcy
 * @date 2019-11-18
 */
public class ScanUtils {

    private static Logger logger = LoggerFactory.getLogger(ScanUtils.class);

    private String appId;

    private String apiKey;

    private String secretkey;

    private static AipFace client ;

    /**
     * 初始化，同时会自动获取access_token（通过AipFace的父级BaseClient）
     * 可以自行查看源码
     */
    public ScanUtils(){
        appId = GlobalConfig.getConfig("scanconf.appId");
        apiKey = GlobalConfig.getConfig("scanconf.apiKey");
        secretkey = GlobalConfig.getConfig("scanconf.secretkey");
        client = new AipFace(appId,apiKey,secretkey);
    }

    /**
     * 人脸注册
     * @param imageUrl
     * @param userId 用户id
     * @param groupId 用户分组
     * @return
     */
    public JSONObject doRegister(String imageUrl, String userId, String groupId) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user1");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE");
        //image 取决于image_type参数，传入BASE64字符串或URL字符串或FACE_TOKEN字符串
        String image = FileUtil.getImageBase64(imageUrl);
        String imageType = "BASE64";
        // 人脸注册
        JSONObject res = client.addUser(image, imageType, groupId, userId, options);
        logger.info("注册接口返回的信息:{}",res);
        return res;

    }


    /**
     * 人脸对比
     * @param image1 拍照的图片
     * @param image2 底图
     * @return JSONObject
     * @author lst
     * @since 2019-12-18
     */
    public JSONObject compareFace(String image1, String image2) {
        String image1Base1 = FileUtil.getImageBase64(image1);
        String image1Base2 = FileUtil.getImageBase64(image2);
        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1Base1, "BASE64");
        MatchRequest req2 = new MatchRequest(image1Base2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);
        JSONObject res = client.match(requests);
        logger.info("注册接口返回的信息:{}",res);
        return res;
    }
}
